from pyglet.gl import *
import window
import background
import pole
import debris
import data
import creatures
import floor
import collision
import particle
import pyglet
from pyglet.window import key
from pyglet import media

import time

#Keys
KEY_PAUSE = key.SPACE
KEY_ESCAPE = key.ESCAPE
KEY_ENTER =  key.ENTER
#Select next hook
KEY_NHOOK = key._1#key.PAGEUP
KEY_PHOOK = key._2#key.PAGEDOWN
KEY_UP = key.UP
KEY_DOWN = key.DOWN
paused = False

class Menu(window.GameState):
    """pause the game"""
    def __init__(self, game):
        self.game = game
        self.game_running = False
        self.menu_selected = ['New Game',
                #'Configure Controls',
                'Exit Game',
                'Resume Game']
        self.menu_items = (('New Game', self.new_game),
        #('Configure Controls', self.configure_controls), 
        ('Exit Game', self.exit_game),
        ('Resume Game', self.resume_game))
        win = window.get_window()
        self.menu_background = data.image("menu.png")
        self.fish_image = data.image("fish1.png")
        self.menu_sprite = pyglet.sprite.Sprite(self.menu_background)
        self.menu_pointer = pyglet.sprite.Sprite(self.fish_image)
        self.menu_sprite.x = (win.width/2) - 200
        self.menu_sprite.y = (win.height/2) - 50 
        self.max_items = len(self.menu_selected) -1
        self.menu_current_item = 0
        win = window.get_window()
        self.message = "Pause"
        #Print menu when you get in here.
        data.sound('chipmunk.mp3').play()
        
    def on_key_press(self, symbol, modifiers):
        data.sound('hit.mp3').play()
        # Overrides default Escape key behaviour
        if symbol == KEY_ENTER:
            #Call function mapped to menu item
            self.menu_items[self.menu_current_item][1]()
        if symbol == KEY_PAUSE: 
            paused = False
            win = window.get_window()
            win.pop_state()
        if symbol == KEY_ESCAPE:
            win = window.get_window()
            win.pop_state()
        if symbol == KEY_UP:
            #print self.menu_current_item
            if not ((self.menu_current_item < 0) or (self.menu_current_item >= self.max_items)):
                self.menu_current_item += 1

        if symbol == KEY_DOWN:
            #print self.menu_current_item
            if not ((self.menu_current_item <= 0) or (self.menu_current_item > self.max_items)):
                self.menu_current_item -= 1

    def new_game(self):
        if self.game == None:
            win = window.get_window()
            win.push_state(Game())
        else:
            #self.game.music_player.stop()
            win = window.get_window()
            win.push_state(Game())
            pass
    def configure_controls(self):
        """Configure game controls"""
        pass
    def exit_game(self):
        """Exit the Game"""
        win = window.get_window()
        win.pop_state()
        win.pop_state()
    def resume_game(self):
        """Resume the game"""
        self.game.music_player.play()
        self.game.background_player.play()
        win = window.get_window()
        win.pop_state()
    def draw_menu(self):
        """Draw all menu_items"""
        win = window.get_window()

        menu_position_y =  self.menu_sprite.y + 50
        menu_position_x =  self.menu_sprite.x + 100 
        #Distance between each menu segment 
        item_height = 35
        default_font_size = 20
        selected_font_size = 25
        menu_title = pyglet.text.Label("Fishing Frenzy", color=(0, 200, 0, 255), 
                    font_size=30, 
                    x = self.menu_sprite.x + 60,
                    y = self.menu_sprite.y + 160)        
        menu_title.draw()
        for key, item in self.menu_items:
            font_size=default_font_size
            if self.menu_selected[self.menu_current_item] == key:
                self.menu_pointer.x = menu_position_x - 80
                self.menu_pointer.y = menu_position_y
                font_size=selected_font_size
            item_segment = pyglet.text.Label(key, color=(0, 200, 0, 255), 
                    font_size=font_size, 
                    x = menu_position_x,
                    y = menu_position_y)
            menu_position_y += item_height
            self.menu_pointer.draw()
            item_segment.draw()
    def on_draw(self):
        window.clear_window()
        self.game.background.draw(self.game)
        self.menu_sprite.draw()
        self.draw_menu()
        #self.menu_item.draw()
    def enter(self, window):
        self.game.music_player.pause()
        self.game.background_player.pause()
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_LINE_SMOOTH)
        glDisable(GL_DEPTH_TEST)
        self.on_resize(window.width, window.height)
        window.set_exclusive_mouse(True)
    def on_resize(self, width, height):
        """Set perspective projecion for fish animation"""
        #TODO (CCB): Caclucate the z-value so that this projection works with all window sizes!
        self.width = width
        self.height = height
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        gluPerspective(60., width / float(height), 0.001, 1000.)
        glMatrixMode(GL_MODELVIEW)        
        glLoadIdentity()
        gluLookAt(width/2.0, height/2.0, 520.0, width/2.0, height/2.0, 0.0, 0.0, 1.0, 0.0) 
class Game(window.GameState):
    """Main game state"""

    MAX_CAST_SPEED = 15
    CAST_SPEED = 0.15
    WATER_LEVEL = 0.7

    def __init__(self):
        self.game_over = False
        self.collision_system = collision.CollisionSystem()
        win = window.get_window()
        self.width = win.width
        self.height = win.height
        # Setup the background audio player
        self.background_player = media.Player()
        self.background_player.volume = 0.2
        self.background_player.play()
        self.background_player.queue(data.sound('beach_sound_effect.mp3'))
        self.background_player.queue(data.sound('ocean_surf.mp3'))
        self.background_player.queue(data.sound('ship_in_heavy_sea.mp3'))
        # Setup the music audio player
        self.music_player = media.Player()
        self.music_player.eos_action = media.Player.EOS_LOOP
        self.music_player.volume = 0.5
        self.music_player.play()
        self.music_player.queue(data.sound('start.mp3'))
        #self.space.resize_static_hash() # Not sure if we need these...
        #self.space.resize_active_hash()

        # Intialize some shared contants
        self.water_level = self.height * self.WATER_LEVEL

        # Initialize game objects
        particle.init(self)
        self.background = background.Background(self)
        self.sea_floor = floor.SeaFloor(self)
        self.creatures = creatures.Sprites(self)
        self.pole = pole.FishingPole(self)
        self.debris = debris.Debris(self)
        
        self.score = 0
        self.score_label = pyglet.text.Label('Score %d'%self.score, color=(0, 200, 0, 255), font_size=20, x = self.width - 140, y =  50)
        
        self.time_color = (200, 0, 0, 255)
        self.time = 60.0 * 5 #5 Minutes
        self.time_label = pyglet.text.Label('', color=self.time_color, font_size = 20, x = self.width - 100, y = 10)
        self.set_label_time()
        
    def set_label_time(self):        
        if self.game_over:
            self.time_label.text = 'GAME OVER'
            self.time_label.x = 300

        else:
            minutes, seconds = divmod(self.time, 60)
            self.time_label.text = '%d:%02d'%(minutes, seconds)
    
    def update_score(self, amt):
        if not self.game_over:
            self.score += amt
        self.score_label.text = 'Score %d'%self.score

    def enter(self, window):
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_LINE_SMOOTH)
        glDisable(GL_DEPTH_TEST)
        self.on_resize(window.width, window.height)
        window.set_exclusive_mouse(True)
        self.timestamp = time.time()
        pyglet.clock.schedule_interval(self.update_time, 1)

    def exit(self, window):
        window.set_exclusive_mouse(False)
    
    def update(self, dt):
        self.background.update(dt)
        self.creatures.update(dt)
        self.pole.update(dt)
        self.debris.update(dt)
        particle.update(dt)
        self.collision_system.collide(self.pole.line)
        #self.debris.collide(self.pole.line)
        #if self.pole.line.hook =="Hook":
        #    self.collision_system.collide(self.pole.line)
        #if self.pole.line.hook =="Dynamite":
        #    print "boom"
        #    self.debris.collide(self.pole.line)

    def update_time(self, dt):
        t = time.time()
        delta = t - self.timestamp
        self.time -= delta
        if self.time < 0:
            self.game_over = True
        self.timestamp = t
        self.set_label_time()
        
    def on_resize(self, width, height):
        """Set perspective projecion for fish animation"""
        #TODO (CCB): Caclucate the z-value so that this projection works with all window sizes!
        self.width = width
        self.height = height
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        gluPerspective(60., width / float(height), 0.001, 1000.)
        glMatrixMode(GL_MODELVIEW)        
        glLoadIdentity()
        gluLookAt(width/2.0, height/2.0, 520.0, width/2.0, height/2.0, 0.0, 0.0, 1.0, 0.0)        
        
        self.background.resize(self)
    
    def on_draw(self):
        window.clear_window()
        self.background.draw(self)
        self.pole.draw(self)
        self.creatures.draw()
        self.debris.draw()
        particle.draw()
        self.score_label.draw()
        self.draw_time()
        #self.sea_floor.draw() # XXX debug
        #self.collision_system.draw() # XXX debug

    def draw_time(self):
        r, g, b, a = self.time_color
        self.time_label.color = self.time_color
        if g > 0:
            g-=2
            self.time_color = (r, g, b, a)
        self.time_label.draw()
        
        
    def on_key_press(self, symbol, modifiers):

        if symbol == KEY_NHOOK:
            #print "Next hook"
            self.pole.line.switch_hook(1)
        if symbol == KEY_PHOOK:
            #print "previous hook"
            self.pole.line.switch_hook(2)

        if symbol == KEY_PAUSE:
          if not paused:
              pyglet.clock.unschedule(self.update_time)
              win = window.get_window()  
              win.push_state(Menu(self))
        elif symbol == key.ESCAPE:
            win = window.get_window()
            win.pop_state()

    def on_mouse_press(self, x, y, buttons, modifiers):
        if not self.pole.is_line_dangling():
            self.pole.reel_in()

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        theta = min(max(-dx * self.CAST_SPEED, -self.MAX_CAST_SPEED), self.MAX_CAST_SPEED)
        self.pole.rotate(theta)

    def on_mouse_release(self, x, y, button, modifiers):
        self.pole.start_cast()

    def on_mouse_scroll(self, x, y, dx, dy):
        if dy < 0:
            self.pole.crank()

